'use strict'

const Jwt = require('jsonwebtoken');

const ApiClient = require('../server/taobao.js').ApiClient;//淘宝API
const fs = require('fs');//文件操作


//微信
var WxApi = require('../server/wxApi');
var config = {
    appId: 'wx6d5c659db53fee95',
    appSecret: 'd62213dea308cb61f6c3e5b4fe649468',
    cachepath: 'morefunWxtoken'
}
var wxApi = new WxApi(config,{});

//后台API，可获取头像 
var config2 = {
    app_key:"23164247",
    app_secret:"ea9dbcf8c9dddf13b57fcdd8f1f63b32",
    redirect_uri:"http://vrbuy.ews.m.jaeapp.com/oauth2"
}
var backClient = new ApiClient({
                            'appkey':config2.app_key,
                            'appsecret':config2.app_secret,
                            'url':'http://gw.api.taobao.com/router/rest'
                        });

const _keySecret = 'ioadsfqwefnalsd333kefoajsd221wirasdf2e';//Jwt秘钥

exports.register = function( server , option , next){

    const sequelize = server.app.db;
    const Sequelize = server.app.Sequelize;

    var dataBase = {
        //团购iteam表

        lux_user : sequelize.define('lux_user',{
            user_id:{
                type: Sequelize.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            openid:{
                type: Sequelize.STRING
            },
            mixnick:{
                type: Sequelize.STRING
            },
            is_win:{//所得奖品种类和数量
                type: Sequelize.STRING
            },
            lotterychance:{
                type: Sequelize.INTEGER
            },
            realname:{
                type: Sequelize.STRING
            },
            phone:{
                type: Sequelize.STRING
            },
            address:{
                type: Sequelize.STRING
            }
        },{
            tableName:'lux_user',
            timestamps:true,
            underscoredAll:true
        })
    }

    var dataFn = require('../server/lux')(dataBase,sequelize);

    /*
     *  首页入口
     *
     */
    server.route({
        method:['GET','POST'],
        path: '/index',
        handler:function(request,reply){
            var reData = {};//接口反馈数据
            var options = request.payload||request.url.query||{};

            var content = fs.readFileSync(__dirname.substr(0,Math.max(__dirname.lastIndexOf('\\'),__dirname.lastIndexOf('\/')))+'/public/main.html','utf-8');
            if(!options.code){//获取微信code
                return reply(content);
            }else{//微信
                wxApi.oauth.getAccessToken(options.code, function (err, result) {//获取微信token
                    if(!err){
                        var accessToken = result.data.access_token;
                        var openid = result.data.openid;
                        console.log(openid);
                        content = content.replace('</body>','<input type="hidden" name="m0j1t2" value="'+openid+'">\n<\/body>');
                        //获取头像
                        wxApi.oauth.getUser(openid, function (err, result) {//获取微信用户info
                            if(!err){
                                //更新头像
                                // reobj.userinfo = result;
                                /*if(result.headimgurl==''){
                                    return reply(content)
                                    .header('Set-Cookie',['openid4='+openid]);
                                }else{
                                    dataFn.user.updateOne(openid,'',result.headimgurl.replace('http:','https:')).then((data)=>{
                                        return reply(content)
                                            .header('Set-Cookie',['openid4='+openid]);                                    
                                    });                                    
                                }*/
                                var headimgurl = result.headimgurl.replace('http:','https:');
                                var nickname = result.nickname;
                                content = content.replace('</body>','<input type="hidden" name="m0j1t2Avatar" value="'+headimgurl+'">\n<\/body>');
                                content = content.replace('</body>','<input type="hidden" name="m0j1t2Nickname" value="'+nickname+'">\n<\/body>');
                                return reply(content);
                            }else{
                                console.log(err);
                                return reply(content);
                            }                   
                        });
                    }else{
                        console.log(err);
                        return reply('');
                    }
                });
            }            
        }
    });

    /*
    *   登录接口
    *
    */
    server.route({
        method:['GET','POST'],
        path: '/lux/login',
        handler: function(request,reply){

            var reData = {};//接口反馈数据
            var options = request.payload||request.url.query||{};

            //验证传入参数
            options.mixnick = options.mixnick||'';
            options.openid = options.openid||'';
            if(options.mixnick==''&&options.openid=='') return reply(wrapper(null,4002));

            options.mixnick = decodeURIComponent(options.mixnick);

            //查询用户记录
            var selectUser = options.mixnick ? dataFn.user.selectOneByMixnick(options.mixnick)
                                             : dataFn.user.selectOneByOpenid(options.openid);
            //获取头像链接
            var getAvatar = dataFn.user.getAvatar(options.mixnick,backClient);

            Promise.all([selectUser,getAvatar]).then(result=>{
                if(result[0]===false)   return reply(wrapper(null,4030));//数据库异常处理
                var userData = result[0];
                var linkAvatar = result[1]; //头像链接

                console.log(userData);
                if(userData!=null){//存在该用户反馈数据
                    console.log('****3');
                    reData.token = Jwt.sign({data: {"userId":userData.user_id}}, _keySecret, { expiresIn: 60 * 60 * 24 });
                    reData.chance = userData.lotterychance;
                    reData.avatar = linkAvatar;
                    return reply(wrapper(reData));                        
                }else{//不存在该用户创建记录
                    console.log('****4');
                    var insertUser = options.mixnick ? dataFn.user.insert(options.mixnick,1)
                                                     : dataFn.user.insert(options.openid,2);
                    insertUser.then(userData=>{
                        //验证数据
                        if(userData===false)   return reply(wrapper(null,4030));//数据库异常处理

                        reData.token = Jwt.sign({data: {"userId":userData.user_id}}, _keySecret, { expiresIn: 60 * 60 * 24 });
                        reData.chance = userData.lotterychance;
                        reData.avatar = linkAvatar;
                        return reply(wrapper(reData));

                    }).catch(err=>{
                        console.log(err);
                        return reply(wrapper(null,4031));
                    });
                }

            }).catch(err=>{
                console.log(err);
                return reply(wrapper(null,4031));
            });

        }
    });


    /*
    *   中奖用户信息提交
    */
    server.route({
        method:['GET','POST'],
        path: '/lux/info/submit',
        handler:function(request,reply){
            
            var reData = {};//接口反馈数据
            var options = request.payload||request.url.query||{};//传入参数

            //验证传入参数
            options.realname = options.realname || '';//真实姓名
            options.phone = options.phone || '';//手机号
            options.address = options.address || '';//地址

            //身份验证
            var userId = Util.login(options).userId || '';
            if(userId === '') return reply(wrapper(null,4000));

            dataFn.user.updateOneById(userId,{
                'realname': options.realname,
                'phone': options.phone,
                'address': options.address
            }).then(result=>{
                if(result===false)   return reply(wrapper(null,4030));//数据库异常处理

                return reply(wrapper(reData));
            }).catch(err=>{
                console.log(err);
                return reply(wrapper(null,4031));
            });

        }
    });

    /*
    *   抽奖接口
    */
    server.route({
        method:['GET','POST'],
        path: '/lux/award/get',
        handler:function(request,reply){
            
            var reData = {};//接口反馈数据
            var options = request.payload||request.url.query||{};//传入参数

            //身份验证
            var userId = Util.login(options).userId || '';
            if(userId === '') return reply(wrapper(null,4000));

            var RANDAWARD = 50;//概率
            var TOTALAWARD = 5;//上限

            var selectUser = dataFn.user.selectOneById(userId);
            var countUser = dataFn.user.count({'is_win':1});

            Promise.all([selectUser,countUser]).then(result=>{
                if(result[0]===false||result[1]===false)   return reply(wrapper(null,4030));//数据库异常处理

                var userData = result[0];
                var count = result[1];
                console.log(userData);
                console.log(count);
                if(userData!=null){//存在该用户反馈数据
                    console.log('****3');
                    //无机会
                    if(userData.lotterychance<=0) return reply(wrapper(null,4004));

                    //有机会
                    var rand = Util.randomInt(0,100000);
                    var award = rand<RANDAWARD&&count<=TOTALAWARD?1:0;

                    reData.newAward = award;
                    //更新数据
                    dataFn.user.updateOneById(userId,{
                        'lotterychance': 0,
                        'is_win': award,
                    }).then(updateResult=>{
                        if(updateResult===false)   return reply(wrapper(null,4030));//数据库异常处理

                        return reply(wrapper(reData));
                    }).catch(err=>{
                        console.log(err);
                        return reply(wrapper(null,4031));
                    });
                }else{//不存在该用户创建记录
                    console.log('****4');
                    return reply(wrapper(null,4000));
                }

            }).catch(err=>{
                console.log(err);
                return reply(wrapper(null,4031));
            });

        }
    });

     var Util = {
        login:function(options){
            var token = options.token || '';
            var loginInfo = {};
            try{//无token或者无效token
                loginInfo = Jwt.verify( token , _keySecret );
            }catch(err){
                // console.log(err);
                return {};
            }     
            return loginInfo.data;
        },
        randomInt: function (Min,Max){   
            return(Min + Math.round(Math.random() * (Max - Min)));   
        }  
    }
       
    function wrapper(data,code){
        var reobj = {
            errCode:0,
            msg:'ok'
        }
        if(code){
            reobj.data = data;
            reobj.errCode = code;
            switch(code){
                case 4000:reobj.msg = 'Not login!';break;
                case 4001:reobj.msg = 'No method!';break;
                case 4002:reobj.msg = 'No mixnick or openid!';break;
                case 4003:reobj.msg = 'Invild params!';break;
                case 4004:reobj.msg = 'No chance!';break;
                case 4010:reobj.msg = 'No enough medal!';break;
                case 4011:reobj.msg = 'No remaining award!';break;
                case 4012:reobj.msg = 'Already chanced!';break;
                case 4030:reobj.msg = 'Sql error!';break;
                case 4031:reobj.msg = 'Server error!';break;
                //签到系列
                case 4041:reobj.msg = 'Has already signed!';break;
                case 4042:reobj.msg = 'Game has already done!';break;
                //VR
                case 4051:reobj.msg = 'Game has already done!';break;
            }
        }else{
            reobj.data = data;
        }
        return JSON.stringify(reobj);
    }

	return next();
}

exports.register.attributes = {
	name: 'route-lux'
}